﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Data;

namespace DAL
{
    internal class GenericList<T>
    {
        public List<T> GetAGenelicListOf(DataTable dataTable)
        {
            List<T> genericList = new List<T>();
            Type t = typeof(T);

            PropertyInfo[] pi = t.GetProperties();

            foreach (DataRow row in dataTable.Rows)
            {
                object defaultInstance = Activator.CreateInstance(t);
                foreach (PropertyInfo prop in pi)
                {
                    try
                    {
                        if (dataTable.Columns.Contains(prop.Name))
                        {
                            object columnvalue = row[prop.Name];
                            if (!DBNull.Value.Equals(columnvalue))
                            {
                                prop.SetValue(defaultInstance, columnvalue, null);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("GenericList - GetAGenelicListOf("
                            + t.ToString() + ")" + ex.Message, ex);
                    }
                }
                T myclass = (T)defaultInstance;
                genericList.Add(myclass);
            }
            return genericList;
        }
    }
}
